// components/balance/index.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import { exceedMessageTip, getShopCartStorage, setShopCartStorage } from '../../utils/hooks';
import { getDatetime } from '../../utils/util';
const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  externalClasses: ['custom-overlay', 'custom-balance'],
  properties: {
    businessId: {
      type: String | Number
    },
    startPrice: {
      type: Number
    },
    info: {
      type: Object,
      value: () => {}
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    showShopCart: false,
    totalPrice: '',
    totalNum: '',
    deliveryFee: '',
    shopCartList: [],
    prePrice: '',
    content: '去结算',
    needPrice: 0
  },
  lifetimes: {
    ready() {}
  },
  pageLifetimes: {
    show() {
      const shopCartList = getShopCartStorage();
      this.setData({
        shopCartList
      });
      this.count();
    }
  },
  observers: {
    businessId() {
      this.judgeBalance();
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    //去提交订单页面
    toSubmitOrderPage() {
      const { shopCartList } = this.data;
      if (!shopCartList.length) {
        return;
      }
      let query = [];
      const { orderSource, sourceId, btnName } = this.data.info;
      if (orderSource) query.push('orderSource=' + orderSource);
      if (sourceId) query.push('sourceId=' + sourceId);
      if (btnName) query.push('btnName=' + btnName);
      query = query.length ? '?' + query.join('&') : '';
      wx.navigateTo({
        url: '/subcontract/home/pages/submitOrder/index' + query
      });
    },
    // 显示购物车弹框
    showShopCartPopup() {
      if (this.data.totalNum <= 0) return;
      this.setData({
        showShopCart: true
      });
    },
    // 关闭购物车弹框
    hideShopCartPopup() {
      this.setData({
        showShopCart: false
      });
    },
    // 清空购物车
    clearShop() {
      wx.setStorageSync('shopCartData', JSON.stringify([]));
      wx.setStorageSync('formList', JSON.stringify([]));
      this.setData({
        shopCartList: [],
        showShopCart: false
      });
      this.count();
      this.triggerEvent('clear');
    },
    // 通过数组中是否存在某个值返回对应的索引，不存在就返回-1
    getIndexById(arr, val, prop = 'id') {
      let tempIndex = -1;
      if (Array.isArray(val)) {
        tempIndex = arr.findIndex(item => {
          if (item[prop]) {
            return item[prop].every((item2, index2) => item2 == val[index2]);
          }
        });
      } else {
        arr.find((item, index) => {
          if (item[prop] == val) {
            tempIndex = index;
          }
        });
      }
      return tempIndex;
    },
    // 新增
    addNum(e, val) {
      const item = e.currentTarget.dataset.item;
      // 这里的val是父组件传过来的需要进入购物车的
      let shopCartList = JSON.parse(wx.getStorageSync('shopCartData'));
      // if(shopCartList.length>1&&isDockingEvent(app.globalData['btnList.eventId'])) return
      const eventId = app.globalData['btnList.eventId'];
      if (exceedMessageTip({ eventId, shopCartList })) return;
      let variantId = item && item.variantId;
      let relationVariantIds = item && item.relationVariantIds;
      let goodsId = item && item.goodsId;
      let index = this.getIndexById(shopCartList, variantId, 'variantId');
      // 如果这里有relationVariantId表示是套餐组合,套餐组合需要用relationVariantId里面的数据是否相等来进行判断
      if (relationVariantIds) {
        index = this.getIndexById(shopCartList, relationVariantIds, 'relationVariantIds');
      } else if (val && val.relationVariantIds) {
        index = this.getIndexById(shopCartList, val.relationVariantIds, 'relationVariantIds');
      }

      if (index == -1) {
        shopCartList.push(JSON.parse(JSON.stringify(val)));
      } else {
        const goods = shopCartList[index];
        goods.nums = goods.nums || 0;
        if (val) {
          goods.nums = goods.nums + val.nums;
        } else {
          goods.nums++;
        }
      }
      this.setData({
        shopCartList
      });
      this.count();
      // wx.setStorageSync('shopCartData', JSON.stringify(shopCartList))
      if (!e.flag) {
        const target = Object.assign({}, shopCartList[index], { flag: true, variantId: variantId, goodsId, nums: 1 });
        if (relationVariantIds) {
          this.triggerEvent('addNum', { ...target, relationVariantIds, relationGoodsNames: item.relationGoodsNames });
        } else {
          this.triggerEvent('addNum', target);
        }
      }
    },
    // 减少
    subNum(e) {
      const item = e.currentTarget.dataset.item;
      let shopCartList = JSON.parse(wx.getStorageSync('shopCartData'));
      let variantId = item && item.variantId;
      let goodsId = item && item.goodsId;
      let serverId = item && item.serverId;
      let index = this.getIndexById(shopCartList, variantId, 'variantId');
      let relationVariantIds = item.relationVariantIds;
      if (relationVariantIds) {
        index = this.getIndexById(shopCartList, relationVariantIds, 'relationVariantIds');
      }
      shopCartList[index].nums--;
      if (shopCartList[index].nums <= 0) {
        shopCartList.splice(index, 1);
        this.judgeFormData(item, shopCartList);
      }
      this.setData({
        shopCartList
      });
      this.count();
      // 如果是减去最后一个数据，且本地缓存存在表单数据，就要去掉

      // wx.setStorageSync('shopCartData', JSON.stringify(shopCartList))
      // 确保只执行一次
      if (!e.flag) {
        this.triggerEvent('subNum', { flag: true, variantId, goodsId, serverId });
      }
    },
    // 修改数量
    shopCartChangeNum(e) {
      const {
        currentTarget: {
          dataset: {
            item: { goodsId },
            index
          }
        },
        detail: { value }
      } = e;
      const { shopCartList } = this.data;
      const prop = `shopCartList[${index}].nums`;
      this.setData({
        [prop]: value > 99 ? 99 : Number(value)
      });
      const nums = shopCartList.filter(item => item.goodsId == goodsId).reduce((a, b) => a + b.nums, 0);
      this.count();
      this.triggerEvent('changeNum', { goodsId, nums });
    },
    judgeFormData(item, shopCartList) {
      const { goodsId, attrMark, serverId } = item;
      if (!attrMark) return;

      let formList = wx.getStorageSync('formList');
      formList = formList ? JSON.parse(formList) : [];
      if (!formList.length) return;

      const id = goodsId + '-' + serverId;
      const length = shopCartList.filter(item => item.goodsId + '-' + serverId == id).length;
      if (length >= 1) return;
      const index = formList.findIndex(item => item.id == id);
      if (index != -1) {
        formList.splice(index, 1);
        wx.setStorageSync('formList', JSON.stringify(formList));
      }
    },
    // 计算活动
    calcuActive() {
      const { shopCartList } = this.data;
      const arr = [];
      // 先合并相同活动的产品,arr是一个二维数组，同时添加折扣
      shopCartList.forEach(item => {
        if (!this.activeTime(item)) {
          // 没有活动或者活动不在时间内，活动产品优惠数量全部置0
          item.activeDiscount = '';
          item.activeNums = 0;
          return;
        }
        // 添加折扣，这里的折扣是用活动价除以原价，而不是除以售价
        item.activeDiscount = parseFloat(((item.active.activePrice / item.price) * 10).toFixed(2)) || 0.01;
        const index = arr.findIndex(item2 => {
          if (item2.length) {
            return item2.some(item3 => item3.active.activeId == item.active.activeId);
          }
        });
        if (index != -1) {
          arr[index].push(item);
        } else {
          arr.push([item]);
        }
      });
      // 根据活动价和售价差排序，差最大的排在最前面
      arr.forEach(item => {
        item.sort((a, b) => b.salePrice - b.active.activePrice - (a.salePrice - a.active.activePrice));
      });

      // 给每个活动产品添加可优惠的个数
      arr.forEach(item => {
        // 每个活动可优惠的最大个数
        let maxCount = item[0].active.maxCount;

        item.forEach(item2 => {
          let maxNum = item2.active.maxNum;
          if (!maxCount) {
            // 数量全部安排完了
            delete item2.activeDiscount;
            delete item2.activeNums;
            return true;
          }
          if (item2.nums <= maxCount) {
            if (item2.nums <= maxNum) {
              item2.activeNums = item2.nums;
            } else {
              item2.activeNums = maxNum;
            }
          } else if (maxCount < item2.nums) {
            if (maxCount >= maxNum) {
              item2.activeNums = maxNum;
            } else {
              item2.activeNums = maxCount;
            }
          }
          maxCount = maxCount - item2.activeNums;
        });
      });

      this.setData({
        shopCartList
      });
    },
    // 计算总价
    getTotalPrice() {
      let totalNum = this.data.shopCartList.filter(item => item.nums).reduce((a, b) => a + b.nums, 0);
      let totalPrice = this.data.shopCartList
        .filter(item => item.nums && item.salePrice > 0)
        .reduce((a, b) => {
          if (b.activeNums) {
            // 这里需要计算活动产品和普通产品
            return (
              a +
              b.salePrice * (b.nums - b.activeNums) +
              b.active.activePrice * b.activeNums +
              b.nums * (b.deposit ? b.deposit : 0)
            );
          } else {
            return a + b.salePrice * b.nums + b.nums * (b.deposit ? b.deposit : 0);
          }
        }, 0);
      // 去掉多余的小数
      this.setData({
        totalNum: totalNum,
        totalPrice: parseFloat(totalPrice.toFixed(2))
      });

      if (totalNum <= 0) {
        this.setData({
          showShopCart: false
        });
      }
    },
    // 计算优惠的总价格
    preferentialPrice() {
      const { totalPrice } = this.data;
      const { shopCartList } = this.data;
      let amount = shopCartList.reduce((a, b) => a + Number(b.price) * b.nums, 0);
      this.setData({
        prePrice: parseFloat((amount - totalPrice).toFixed(2))
      });
    },
    judgeBalance() {
      let content = '';
      const { totalNum } = this.data;
      this.judgeStartPrice();
      if (!totalNum) content = '未选择产品';
      if (totalNum) content = '去结算';
      this.setData({
        content
      });
    },
    // 是否差起步价
    judgeStartPrice() {
      const { shopCartList, businessId, startPrice } = this.data;

      if (!businessId) return;
      const arr = shopCartList.filter(item => item.businessId == businessId);

      if (arr.length) {
        const price = arr.reduce((a, b) => {
          if (b.activeDiscount) {
            return a + b.activeNums * b.active.activePrice + (b.nums - b.activeNums) * b.salePrice;
          } else {
            return a + b.nums * b.salePrice;
          }
        }, 0);
        this.setData({
          needPrice: price < startPrice ? parseFloat((startPrice - price).toFixed(2)) : 0
        });
      } else {
        this.setData({
          needPrice: 0
        });
      }
    },
    // 判断是不是在活动范围之内
    activeTime(item) {
      if (!item.active) return;
      let { beginDate, endDate } = item.active;
      beginDate = getDatetime(beginDate).getTime();
      endDate = getDatetime(endDate).getTime();
      let nowDate = new Date().getTime();
      return nowDate > beginDate && nowDate < endDate;
    },
    // 不在可售时间之内
    timeOut(goodsId) {
      let { shopCartList } = this.data;
      shopCartList = shopCartList.filter(item => item.goodsId != goodsId);
      this.setData({
        shopCartList
      });
      Toast.fail('产品处于非可售时间');
      this.count();
      wx.setStorageSync('shopCartData', JSON.stringify(shopCartList));
    },
    /**
     * @description 输入数量一定已经有一个商品了，所以购物车一定是已经存在商品了的
     */
    // numChange(e,nums){
    //   let shopCartList = JSON.parse(wx.getStorageSync('shopCartData'))
    //   let id = e.currentTarget.dataset.id
    //   let goodsId = e.currentTarget.dataset.goodsid
    //   nums = Number(e.detail.value)||nums||0
    //   let index = this.getIndexById(shopCartList,id,"variantId")
    //   shopCartList[index].nums = nums
    //   this.setData({
    //     shopCartList,
    //   })
    //   this.count()
    //   if(!e.flag){
    //       this.triggerEvent("numChange",{flag:true,id:id,nums:nums,goodsId:goodsId})
    //   }
    //   wx.setStorageSync('shopCartData', JSON.stringify(shopCartList))
    // },
    // 计算
    count(shopCartList) {
      // 活动
      this.calcuActive();
      // 计算总价
      this.getTotalPrice();
      // 计算优惠的价格
      this.preferentialPrice();
      // 判断是否可以结算
      this.judgeBalance();
      shopCartList = (shopCartList || this.data.shopCartList).filter(item => item.nums);
      setShopCartStorage(shopCartList);
    }
  }
});
